package com.example.ds.base;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.example.ds.utils.WrapperUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * Controller基类
 *
 * @author 姚勇
 */
@Slf4j
@SuppressWarnings("all")
public abstract class BaseController<T extends BaseEntity, S extends IService<T>> {

    @Autowired
    S service;

    @Autowired
    private HttpServletRequest request;

    @PostMapping("/save")
    public ResponseEntity<Boolean> save(T t) {
        return ResponseEntity.ok(service.save(t));
    }

    @PutMapping("/update")
    public ResponseEntity<Boolean> update(T t) {
        UpdateWrapper wrapper = getUpdateWrapper(t);
        t.setUpdated(LocalDateTime.now());
        return ResponseEntity.ok(service.update(t, wrapper));

    }

    @GetMapping("/get/{id}")
    public ResponseEntity<T> get(@PathVariable("id") String id) {
        return ResponseEntity.ok(service.getById(id));
    }

    @DeleteMapping("/delete")
    public ResponseEntity<Boolean> delete(String id) {
        return ResponseEntity.ok(service.removeById(id));
    }

    @GetMapping("/listPage")
    public ResponseEntity<Page<T>> listPage(@RequestParam(name = "page", defaultValue = "1") Integer pageNo,
                                            @RequestParam(name = "rows", defaultValue = "10") Integer pageSize, T t) {

        Page<T> page = new Page<>(pageNo, pageSize);
        Wrapper<T> queryWrapper = getQueryWrapper(t);
        Page<T> pageList = service.page(page, queryWrapper);
        return ResponseEntity.ok(pageList);
    }

    @GetMapping("/listMaps")
    public ResponseEntity<List<Map<String, Object>>> listMaps(T t) {
        Wrapper<T> queryWrapper = getQueryWrapper(t);
        List<Map<String, Object>> list = service.listMaps(queryWrapper);
        return ResponseEntity.ok(list);
    }

    /**
     * 让子类重写该方法,组装查询条件
     */
    public QueryWrapper<T> getQueryWrapper(T t) {
        return WrapperUtil.initQueryWrapper(t, request);
    }

    public UpdateWrapper<T> getUpdateWrapper(T t) {
        return WrapperUtil.initUpdateWrapper(t);
    }

}

